package com.apes.fn.fico.debitnote.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.fn.scm.contract.FnContract;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.DateUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.finance.model.Bank;
import com.apes.scm.masterdata.finance.model.BankAccount;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.AccessProvider;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 营业预借支单
 * Creator: zouyc
 * CreateDate: 2019-12-20 10:18
 * Description:
 **/
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = BusinessDebitNote.CONST_TABLE_NAME)
public class BusinessDebitNote extends Model {
    public static final String CONST_TABLE_NAME = "fn_business_debit_note";

    @Id
    @Column(name = "id", length = 30)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "营业款预支单编码", padding = 8)
    @Comment("预支单编码")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    @Comment("商户下销售部门")
    private Dept saleDept;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "contract_id", referencedColumnName = "id")
    @Comment("赋能合同编码")
    private FnContract contract;


    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "valid_from")
    @Comment("合同开始日期")
    private Date validFrom;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "valid_period")
    @Comment("合同结束")
    private Date validPeriod;


    @Column(name = "remarks", length = 200)
    @Comment("备注")
    private String remarks;

    @States(name = "单据状态", values = {
            @State(id = "create", name = "创建"),
            @State(id = "apply", name = "提交"),
            @State(id = "pending", name = "待排款"),
            @State(id = "arrangement", name = "排款中"),
            @State(id = "pay", name = "部分付款"),
            @State(id = "paid", name = "已付款"),
    })
    @Column(name = "state", length = 36, nullable = false)
    private String state;

    @States(name = "单据状态", values = {
            @State(id = "unwithheld", name = "未扣收"),
            @State(id = "partialDeduction", name = "部分扣收"),
            @State(id = "paidOff", name = "已扣收"),
    })
    @Column(name = "withhold", length = 36)
    @Comment("扣收状态")
    private String withhold;
    /**
     * 商户信息
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fn_customer_id", referencedColumnName = "id", nullable = false)
    @Comment("商户")
    private PartyRole fnCustomer;


    @Comment("接入商")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "access_provider_id", referencedColumnName = "id", nullable = false)
    private AccessProvider accessProvider;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "access_date")
    @Comment("接入日期")
    private Date accessDate;

    @Column(name = "number_of_store")
    @Comment("门店数量")
    private Integer numberOfStore;

    @Column(name = "note", length = 500)
    @Comment("备注")
    private String note;

    @Column(name = "guaranteed_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("保证金额度")
    private double guaranteedAmount = 0;

    @Column(name = "standing_inventory_deposit", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("常备库存订金")
    private double standingInventoryDeposit = 0;

    @Column(name = "standing_inventory_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("常备库存金额")
    private double standingInventoryAmount = 0;

    @Column(name = "un_deducted_loan_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("未扣收预支金额")
    private double unDeductedLoanAmount = 0;

    @Column(name = "un_deducted_budget_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("上期未扣收营业款")
    private double unDeductedBudgetAmount = 0;


    @Column(name = "total_un_deducted_cost", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("分期剩余未扣收金额")
    private double totalUnDeductedCost = 0;

    @Column(name = "un_buckled_budget_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("已扣收预支金额")
    private double unBuckledBudgetAmount = 0;

    @Column(name = "last_month_turnover", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("上月营业额")
    private double lastMonthTurnover = 0;

    @Column(name = "current_month_turnover", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("营业收入")
    private double currentMonthTurnover = 0;

    @Column(name = "available_loan", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("可预支额度")
    private double availableLoan = 0;

    //可预支额度 = 营业收入-营业支出+上期未扣收营业款-分期剩余未扣收金额-预留金额


    @Column(name = "amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("预留金额")
    private double amount = 0;


    /**
     * 借款信息
     */
    @Column(name = "reason", length = 500)
    @Comment("预支说明")
    private String reason;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "limit_date")
    @Comment("预支期止")
    private Date limitDate;

    @Column(name = "price_debit", nullable = false, columnDefinition = "NUMBER(16,4) DEFAULT 0")
    @Comment("预支金额")
    private double priceDebit = 0.0;

    @Column(name = "principal_repaid", nullable = false, columnDefinition = "NUMBER(16,4) DEFAULT 0")
    @Comment("已付款")
    private double principalRepaid = 0.0;

    @Column(name = "unpaid_principal", nullable = false, columnDefinition = "NUMBER(16,4) DEFAULT 0")
    @Comment("未付款")
    private double unpaidPrincipal = 0.0;

    @Column(name = "prepaid_principal", nullable = false, columnDefinition = "NUMBER(16,4) DEFAULT 0")
    @Comment("预还本金")
    private double prepaidPrincipal = 0.0;

    @Column(name = "annual_rate", columnDefinition = "NUMBER(8,4) DEFAULT 0")
    @Comment("年利率")
    private double annualRate = 0.0;

    @Column(name = "capital_balance", columnDefinition = "NUMBER(16,2) DEFAULT 0")
    @Comment("实预支金额")
    private double capitalBalance = 0.0;

    @Column(name = "interest_balance", columnDefinition = "NUMBER(16,2)DEFAULT 0")
    @Comment("利息余额")
    private double interestBalance = 0.0;

    @Column(name = "cost_amount", columnDefinition = "NUMBER(16,2)DEFAULT 0")
    @Comment("营业支出")
    private double costAmount = 0.0;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "borrowing_date")
    @Comment("预支期起")
    private Date borrowingDate;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "loan_repayment_date")
    @Comment("对账单清账日期")
    private Date loanRepaymentDate;


    /**
     * 操作信息
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "submit_uid", referencedColumnName = "id")
    @Comment("提交人")
    private PartyRole submitUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "submit_date")
    @Comment("提交日期")
    private Date submitDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审批人")
    private PartyRole approveUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "approve_date")
    @Comment("审批日期")
    private Date approveDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "loan_uid", referencedColumnName = "id")
    @Comment("放款确认人")
    private PartyRole loanUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "loan_date")
    @Comment("付款日期")
    private Date loanDate;

    @Column(name = "is_loan", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE, nullable = false)
    @Comment("是否放款")
    private boolean loan = false;

    @Comment("银行账户")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "bank_account_id", referencedColumnName = "id", nullable = false)
    private BankAccount bankAccount;

    @Column(name = "count")
    @Comment("OA流程")
    private int count = 1;

    /**
     * 户名
     */
    @Column(name = "account_name")
    @Comment("银行账户")
    private String accountName;

    @Name
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fn_tag", referencedColumnName = "id")
    @Comment("赋能标签")
    private Enumeration fnTag;

    @Transient
    private String bankAccountName;

    @Transient
    public String getBankAccountName() {
        if (this.bankAccount == null) return null;
        return this.bankAccount.getAccountName();
    }

    /**
     * 银行账户id
     */
    @Column(name = "account_id")
    @Comment("银行账户")
    private String accountId;

    @Column(name = "disbursement_already_amount", columnDefinition = ApesConst.FIELD_16_4)
    @Comment("已排款金额")
    private double disbursementAlreadyAmount = 0;

    @Comment("付款回执")
    @Column(name = "file_address", length = 4000)
    private String fileAddres;

    /**
     * 银行
     */
    @Comment("银行")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "bank_id", referencedColumnName = "id", nullable = false)
    private Bank bank;

    @OneToMany(mappedBy = "businessDebitNote", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<DeductionDetail> deductionDetails = new ArrayList<>();

    public List<DeductionDetail> getDeductionDetails() {
        if (deductionDetails == null) deductionDetails = new ArrayList<>();
        for (DeductionDetail deductionDetail : deductionDetails) {
            deductionDetail.setBusinessDebitNote(this);
        }
        return deductionDetails.stream().sorted(Comparator.comparing(DeductionDetail :: getCreateDate).reversed()).collect(Collectors.toList());
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }

    public void computeAmt() {
        availableLoan = 0;
        availableLoan = currentMonthTurnover - unDeductedLoanAmount;
    }


    @Transient
    private boolean pic;
}
